package com.map.core.utils;

import com.map.modules.controller.ConfigController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;

@Slf4j
public class FileUtils {

    /**
     *
     * @param dirPath 文件所在的目录
     * @return 查找目标文件
     * @throws FileNotFoundException
     */
    public static File findFile(String dirPath, String targetName) throws FileNotFoundException {
        File dirFile = new File(dirPath);
        if(null == dirFile || !dirFile.isDirectory()) {
            throw new FileNotFoundException(dirPath + "文件夹不存在！");
        }
        String targetSuffix = targetName.substring(targetName.lastIndexOf("."));
        for(File file : dirFile.listFiles()) {
            String fileName = file.getName();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            if(targetSuffix.equals(suffixName)) {
                if(targetName.toLowerCase().equals(fileName.toLowerCase())) {
                    return file;
                }
            }
        }
        return null;
    }

    /**
     * 获取当前安装目录下的Resources文件夹路径
     * @return
     */
    public static String getClassesPath() {
        if(ConfigController.isOSLinux()) {
            //文件夹不存在，就先创建文件夹
            return dirExist("/usr/local/java_service/");
        } else {
            URL resource = FileUtils.class.getClassLoader().getResource("");
            if (null == resource) {
                log.error("there is no resources in src dir! someone getClassesPath failed.");
                return "";
            }
            return resource.getPath();
        }
    }

    public static String dirExist(String filePath) {
        File file = new File(filePath);
        if(!file.exists()){
            file.mkdir();
        }
        return filePath;
    }
    /**
     * 根据文件的绝对路径，获取其目录
     * @param absolutePathPath
     * @return
     */
    public static String getBaseDir(String absolutePathPath) {
        if (StringUtils.isEmpty(absolutePathPath)) {
            return "";
        }
        if (absolutePathPath.contains("\\")) {
            return absolutePathPath.substring(0, absolutePathPath.lastIndexOf("\\"));
        }
        return absolutePathPath.substring(0, absolutePathPath.lastIndexOf("/"));
    }

    public static void closeStream(Closeable stream) {
        if(null != stream) {
            try {
                stream.close();
            } catch (IOException e) {

            }
        }
    }
}
